function [F] = StateTrans(AllStatesMap,P)
% Compute state transition matrix for Model 1. Each (n,m) element is the prob of moving from 
% state n to state m.

% The first tthing to note is that you can't go from one exogenous fixed
% state to another. So the final transition matrix will be block diagonal, 
% with the same blocks actually, since being in a given fixed state does
% not change the transition probabilities for other states.

% First we will build each block, then block diagonalize it to get the
% final transition.

NoFixedState = AllStatesMap(AllStatesMap(:,end)==1 & AllStatesMap(:,end-1)==1,:); % Number of states, not including fixed exogenous states and SRD.
nstates = size(NoFixedState,1);

F{1} = zeros(nstates); F{2} = F{1}; F{3} = F{1};% Set up state transition matrices.
% First, a=0, that is, fields in the outside option:
V0 = (NoFixedState(:,1) == 1); % First column stores age state.
V1 = (NoFixedState(:,1) == 2);

% Each element of F_ is the probability you go from row state to column. 
% Starting from the outside option.
F{1}(V0,V0) = P; % Stay in outside option
F{2}(V0,V1) = P; % Plant sugarcane

maxage = max(NoFixedState(:,1));
for a=2:maxage-1
    Va  = (NoFixedState(:,1) == a);
    Va1 = (NoFixedState(:,1) == a+1);
    F{1}(Va,Va1) = P; % Do not replant, but keep sugarcane
    F{2}(Va,V1)  = P; % Replant sugarcane
    F{3}(Va,V0)  = P; % Abandon sugarcane crop
end
% Finally, for a=max(a):
Va  = (NoFixedState(:,1) == maxage);
F{1}(Va,Va) = P;
F{2}(Va,V1) = P;
F{3}(Va,V0) = P;

nfx_states = length(unique([AllStatesMap(:,end-1) AllStatesMap(:,end)],'rows'));

G = speye(nfx_states);

for a=1:3
    F{a} = kron(G,F{a});
end

end